package com.yafeng.shiro;

import com.yafeng.logic.entity.UserOprator;
import com.yafeng.logic.mapper.UserOperatorMapper;
import com.yafeng.logic.service.UserOperatorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


@Slf4j
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserOperatorService userOperatorService;

    private static final String encryptSalt = "F12839WhsnnEV$#23b";
    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {

        return token instanceof UsernamePasswordToken;

    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("授权");
        //String username = JwtUtils.getUsername(principals.toString());
        // UserBean user = userService.queryUserById(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // simpleAuthorizationInfo.addRole(user.getRole());
        // Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(",")));
        // simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     * 我们可以看到doGetAuthenticationInfo里面只判断了用户存不存在，其实也没做密码比对，
     * 只是把数据库的数据封装一下就返回了。
     * 真正的比对逻辑在Matcher里实现的，这个shiro已经替我们实现了。如果matcher返回false，shiro会抛出异常，
     * 这样controller那边就会知道验证失败了。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {

        String account = (String)auth.getPrincipal();

        System.out.println("认证="+account);

        UserOprator user = userOperatorService.queryUserById(account);

        if(user == null) throw new AuthenticationException("用户名或者密码错误");
        SimpleAuthenticationInfo authenticationInfo= new SimpleAuthenticationInfo(user, user.getPassword(), "loginRealm");
        return authenticationInfo;

        // return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(encryptSalt), "loginRealm");
    }

}


















